import path from 'path'
import ts from 'rollup-plugin-typescript2'
import scss from 'rollup-plugin-scss';
import postcss from 'rollup-plugin-postcss'
import { nodeResolve } from '@rollup/plugin-node-resolve';

const masterVersion = require('./package.json').version
const packagesDir = path.resolve(__dirname, 'components')
const packageDir = path.resolve(packagesDir, process.env.TARGET)
const resolve = p => path.resolve(packageDir, p)
const pkg = require(resolve(`package.json`))
const packageOptions = pkg.buildOptions || {}
const name = path.basename(packageDir)

const defaultFormats = ['esm', 'cjs']
const packageFormats = packageOptions.formats || defaultFormats
const packageConfigs = packageFormats.map(format => {
  return createConfig({
    file: resolve(`dist/index.${format}.js`),
    format
  })
})

export default packageConfigs


function createConfig(output, plugins = []) {
  const format = output.format

  if (!output) {
    console.log(require('chalk').yellow(`invalid format: "${format}"`))
    process.exit(1)
  }

  output.exports = 'named'
  output.sourcemap = true
  output.externalLiveBindings = false
  output.name = packageOptions.name

  const external = []
  const nodePlugins = [nodeResolve()]

  if (output.format == 'iife') {
    external.push(...['source-map', '@babel/parser', 'estree-walker'])
  } else {
    external.push(...[
      ...Object.keys(pkg.dependencies || {}),
      ...Object.keys(pkg.peerDependencies || {}),
    ])
  }

  const tsPlugin = ts({
    check: process.env.NODE_ENV === 'production' && !hasTSChecked,
    tsconfig: path.resolve(__dirname, 'tsconfig.json'),
    cacheRoot: path.resolve(__dirname, 'node_modules/.rts2_cache'),
    tsconfigOverride: {
      compilerOptions: {
        sourceMap: output.sourcemap,
        // declaration: true,
        // declarationMap: true
      },
      exclude: ['**/__tests__', 'test-dts']
    }
  })

  return {
    input: resolve('index.ts'),
    output,
    external,
    plugins: [
      tsPlugin,
      // scss({
      //   outputStyle: 'compressed',
      // }),
      postcss({ minimize: true }),
      ...nodePlugins,
      ...plugins,
    ],
  }
}